using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using HandyControlUIDemo.tools;
using PasswordBox = HandyControl.Controls.PasswordBox;
using TextBox = HandyControl.Controls.TextBox;
using Window = System.Windows.Window;

namespace HandyControlUIDemo.Windows;

public partial class PasswordBoxWindow : Window
{
    public PasswordBoxWindow()
    {
        InitializeComponent();
    }

    protected override void OnContentRendered(EventArgs e)
    {
        base.OnContentRendered(e);
        var textBox = ReflectUtils.GetPrivateField<System.Windows.Controls.TextBox>(HcPasswordBox,"_textBox");
        Console.WriteLine($"innerTextBox={textBox}");
        textBox.Foreground = Brushes.Red;
    }
    
  
    /// <summary>
    /// 递归打印控件树
    /// </summary>
    /// <param name="obj">当前的 DependencyObject</param>
    /// <param name="level">当前层次级别</param>
    private void PrintControlHierarchy(DependencyObject obj, int level = 0)
    {
        // 打印当前对象的信息
        string indent = new String(' ', level * 2); // 用于缩进的空格
        Console.WriteLine($"{indent}Type: {obj.GetType().Name}-{obj.GetType().Namespace}");

        // 获取子对象数量
        int childrenCount = VisualTreeHelper.GetChildrenCount(obj);

        // 遍历子对象
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            PrintControlHierarchy(child, level + 1);
        }
    }
    public static TextBox GetInternalTextBox(PasswordBox passwordBox)
    {
        var visualChildren =  GetVisualChildren(passwordBox).OfType<FrameworkElement>();

        foreach (var child in visualChildren)
        {
            if (child is TextBox textBox)
            {
                return textBox;
            }
        }

        return null;
    }

    public static IEnumerable<DependencyObject> GetVisualChildren(DependencyObject parent)
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            yield return child;

            foreach (var grandChild in GetVisualChildren(child))
            {
                yield return grandChild;
            }
        }
    }
}
 
 